home *** CD-ROM | disk | FTP | other *** search
/ Graphics Plus / Graphics Plus.iso / info / rtnews / rtnv5n3 < prev    next >
Encoding:
Text File  |  1994-10-16  |  37.6 KB  |  1,000 lines

  1.  _ __                 ______                         _ __
  2. ' )  )                  /                           ' )  )
  3.  /--' __.  __  ,     --/ __  __.  _. o ____  _,      /  / _  , , , _
  4. /  \_(_/|_/ (_/_    (_/ / (_(_/|_(__<_/ / <_(_)_    /  (_</_(_(_/_/_)_
  5.              /                               /|
  6.             '                               |/
  7.  
  8.             "Light Makes Right"
  9.  
  10.              September 2, 1992
  11.             Volume 5, Number 3
  12.  
  13. Compiled by Eric Haines, 3D/Eye Inc, 2359 Triphammer Rd, Ithaca, NY 14850
  14.     erich@eye.com
  15. All contents are copyright (c) 1992 by the individual authors
  16. Archive locations: anonymous FTP at princeton.edu (128.112.128.1)
  17.     /pub/Graphics/RTNews, wuarchive.wustl.edu:/graphics/graphics/RTNews,
  18.     and many others.
  19. UUCP archive access: write Kory Hamzeh (quad.com!avatar!kory) for info.
  20.  
  21. Contents:
  22.     Introduction
  23.     Intersection Between a Line and a Polygon (UNDECIDABLE??), by Dave Baraff,
  24.     Tom Duff
  25.     Fastest Point in Polygon Test, by Aladdin Nassar, Philip Walden, Eric
  26.     Haines, Tom Dickens, Ron Capelli, Sundar Narasimhan, Christopher Jam,
  27.     and (last but not least) Stuart MacMartin
  28.     Polygon Intersection via Barycentric Coordinates, by Peter Shirley
  29.     Many-Sided Polygon Intersection, by Eric Haines, Benjamin Zhu
  30.     Code for Point in Polygon Intersectors, by Eric Haines
  31.  
  32. -------------------------------------------------------------------------------
  33.  
  34. Introduction
  35.  
  36. This special issue is dedicated to everyone's (well, at least my) favorite
  37. computer graphics FAQ:  how do you find if a given point is inside a polygon?
  38. John Griegg's FAQ posting points at _An Introduction to Ray Tracing_, edited
  39. by Andrew Glassner.  This issue speeds up that algorithm (count the crossings
  40. of a test ray), and hopefully lays to rest the idea of using the "sum the
  41. angles" algorithm.  Plus there's a little discussion of what to do for special
  42. cases such as triangles and complex polygons, and code for four different ways
  43. to do this test at the end of the issue.
  44.  
  45. -------------------------------------------------------------------------------
  46.  
  47. [To begin this issue, here is one of the better pieces of obfuscatory writing
  48. in the field of computer graphics.  Reprinted from RTNews8 - EAH]
  49.  
  50.  
  51. Intersection Between a Line and a Polygon (UNDECIDABLE??),
  52.     by Dave Baraff, Tom Duff
  53.  
  54.     From: deb@charisma.graphics.cornell.edu
  55.     Newsgroups: comp.graphics
  56.     Keywords: P, NP, Jordan curve separation, Ursyhon Metrization Theorem
  57.     Organization: Program of Computer Graphics
  58.  
  59. In article [...] ncsmith@ndsuvax.UUCP (Timothy Lyle Smith) writes:
  60. >
  61. >  I need to find a formula/algorithm to determine if a line intersects
  62. >  a polygon.  I would prefer a method that would do this in as little
  63. >  time as possible.  I need this for use in a forward raytracing
  64. >  program.
  65.  
  66. I think that this is a very difficult problem.  To start with, lines and
  67. polygons are semi-algebraic sets which both contain uncountable number of
  68. points.  Here are a few off-the-cuff ideas.
  69.  
  70. First, we need to check if the line and the polygon are separated.  Now, the
  71. Jordan curve separation theorem says that the polygon divides the plane into
  72. exactly two open (and thus non-compact) regions.  Thus, the line lies
  73. completely inside the polygon, the line lies completely outside the polygon,
  74. or possibly (but this will rarely happen) the line intersects the polyon.
  75.  
  76. Now, the phrasing of this question says "if a line intersects a polygon", so
  77. this is a decision problem.  One possibility (the decision model approach) is
  78. to reduce the question to some other (well known) problem Q, and then try to
  79. solve Q.  An answer to Q gives an answer to the original decision problem.
  80.  
  81. In recent years, many geometric problems have been successfully modeled in a
  82. new language called PostScript.  (See "PostScript Language", by Adobe Systems
  83. Incorporated, ISBN # 0-201-10179-3, co. 1985).
  84.  
  85. So, given a line L and a polygon P, we can write a PostScript program that
  86. draws the line L and the polygon P, and then "outputs" the answer.  By
  87. "output", we mean the program executes a command called "showpage", which
  88. actually prints a page of paper containing the line and the polygon.  A quick
  89. examination of the paper provides an answer to the reduced problem Q, and thus
  90. the original problem.
  91.  
  92. There are two small problems with this approach.
  93.  
  94.     (1) There is an infinite number of ways to encode L and P into the
  95.     reduced problem Q.  So, we will be forced to invoke the Axiom of
  96.     Choice (or equivalently, Zorn's Lemma).  But the use of the Axiom of
  97.     Choice is not regarded in a very serious light these days.
  98.  
  99.     (2) More importantly, the question arises as to whether or not the
  100.     PostScript program Q will actually output a piece of paper; or in
  101.     other words, will it halt?
  102.  
  103.     Now, PostScript is expressive enough to encode everything that a
  104.     Turing Machine might do; thus the halting problem (for PostScript) is
  105.     undecidable.  It is quite possible that the original problem will turn
  106.     out to be undecidable.
  107.  
  108.  
  109. I won't even begin to go into other difficulties, such as aliasing, finite
  110. precision and running out of ink, paper or both.
  111.  
  112. A couple of references might be:
  113.  
  114. 1. Principia Mathematica.  Newton, I.  Cambridge University Press, Cambridge,
  115.    England.  (Sorry, I don't have an ISBN# for this).
  116.  
  117. 2. An Introduction to Automata Theory, Languages, and Computation.  Hopcroft, J
  118.   and Ulman, J.
  119.  
  120. 3. The C Programming Language. Kernighan, B and Ritchie, D.
  121.  
  122. 4. A Tale of Two Cities. Dickens, C.
  123.  
  124. --------
  125.  
  126. From: td@alice.UUCP (Tom Duff)
  127. Summary: Overkill.
  128. Organization: AT&T Bell Laboratories, Murray Hill NJ
  129.  
  130. The situation is not nearly as bleak as Baraff suggests (he should know
  131. better, he's hung around The Labs for long enough).  By the well known
  132. Dobbin-Dullman reduction (see J. Dullman & D. Dobbin, J. Comp. Obfusc.
  133. 37,ii:  pp. 33-947, lemma 17(a)) line-polygon intersection can be reduced to
  134. Hamiltonian Circuit, without(!) the use of Grobner bases, so LPI (to coin an
  135. acronym) is probably only NP-complete.  Besides, Turing-completeness will no
  136. longer be a problem once our Cray-3 is delivered, since it will be able to
  137. complete an infinite loop in 4 milliseconds (with scatter-gather.)
  138.  
  139. --------
  140.  
  141. From: deb@svax.cs.cornell.edu (David Baraff)
  142.  
  143. Well, sure it's no worse than NP-complete, but that's ONLY if you restrict
  144. yourself to the case where the line satisfies a Lipschitz condition on its
  145. second derivative.  (I think there's an '89 SIGGRAPH paper from Caltech that
  146. deals with this).
  147.  
  148. -------------------------------------------------------------------------------
  149.  
  150. Fastest Point in Polygon Test, by Aladdin Nassar, Philip Walden, Eric Haines,
  151.     Tom Dickens, Ron Capelli, Sundar Narasimhan, Christopher Jam, and
  152.     (last but not least) Stuart MacMartin
  153.  
  154.  
  155. Aladdin Nassar asked a variant on the classic question:
  156.  
  157. What is the MOST EFFICIENT way to find if a point lies within a SIMPLE
  158. polygon given a set of vertices (in no particular order) and the point
  159. coordinate ?   Are there anonymous ftp sites with such canned functions
  160. instead of re-inventing the wheel.  Excuse me if that is a trivial question.
  161.  
  162. ----
  163.  
  164. Philip Walden (pwalden@hpcc01.corp.hp.com) replies:
  165.  
  166. Another alternative to using a test ray is to sum the arc angles from
  167. the vertices to the test point. If the sum is 2pi, the point is inside,
  168. if 0 it's outside. i.e.
  169.  
  170.     give a polygon with a set of vertices v[1:n] an test point p
  171.  
  172.     if (SUM i=1 to n (arcangle(v[i]->p->v[i+1])) > pi
  173.     then p is inside
  174.     else it's outside
  175.  
  176. ----
  177.  
  178. Eric Haines replies:
  179.  
  180. This method turns out to be exceedingly slow, about an order of magnitude
  181. slower than the "shoot a ray and count crossings" method.  The problem is that
  182. the "arcangle" routine takes awhile:  you need to normalize your vectors, you
  183. need to compute the dot product (for the angle) and cross product (for the
  184. sign of the angle), and you need the arccosine of the dot product for the
  185. angle itself.  This is done for every vertex of the polygon.  All of this adds
  186. up!
  187.  
  188. In fact, I wrote a program to test the two algorithms head-to-head when I was
  189. deciding which to use:  code attached (for a switch!).  The test program makes
  190. polygons from 3 to 7 (though you can change this) and random scatters the
  191. vertices from [0-1).  It then tests each of these polygons with a series of
  192. random points from [0-1).
  193.  
  194. I won't claim that either implementation of the angle summation or segment
  195. crossing routines below are optimal (though I do try to share intermediate
  196. results between vertices).  But I don't care how much you tune the angle
  197. summation algorithm:  it's still going to be slower than crossing counting.
  198. Please do tell me of any hacks you make to get either algorithm faster,
  199. anyway.
  200.  
  201. Code's at the end of this issue; you should mess with *_TEST_TIMES however you
  202. see fit.  I found you could set them pretty low, but I felt better when they
  203. were relatively high (i.e. the test times were greater than the granularity
  204. of the "time" command).  The crossing counting inside/outside test is the one
  205. I wrote up in _An Introduction to Ray Tracing_, edited by Andrew Glassner,
  206. Academic Press, plus a trick or two not in the book.
  207.  
  208. I should also mention that the tests below assuming that an even winding
  209. number means that the point is outside, as this is how the Jordan Curve test
  210. is used.  Think of the winding number as the number of loops around a point.
  211. As an example, think of a star shape:  the interior pentagon is considered
  212. "outside" since points in it cross two lines.  You can modify the tests as
  213. shown in the comments if you want to test for just a non-zero winding number
  214. (i.e. the star is fully filled).
  215.  
  216. Timings are shown after the next comment.
  217.  
  218. ----
  219.  
  220. Tom Dickens notes in a related article:
  221.  
  222. Additional logic [in the barycentric test] can be added to avoid checking
  223. triangles which are located in a region which has already been determined to
  224. be beyond of a side of a previous triangle which returned a negative check.
  225.  
  226. [I don't know if such an enhancement is possible (one triangle's outside is
  227. another's inside) if the polygon is not convex, but mention it here for
  228. interest's sake; it is certainly not incorporated in my code.  - EAH]
  229.  
  230. ----
  231.  
  232. comments from Ron Capelli (capelli@vnet.ibm.com):
  233.  
  234. >the "arcangle" routine takes awhile:  you need to normalize your vectors, you
  235. >need to compute the dot product (for the angle) and cross product (for the
  236. >sign of the angle), and you need the arccosine of the dot product for the
  237. >angle itself.  This is done for every vertex of the polygon.
  238.  
  239. See "Fast Approximation to the Arctangent" in Graphics Gems II (p.389).  The
  240. maximum error of this approximation allows polygons with up to about 40
  241. vertexes to be handled safely.
  242.  
  243. No need to normalize, take dot products, or cross products either.  From the
  244. vector components (dx, dy) from a test point to a polygon vertex, get an angle
  245. using arctan (or the fast approximation, in which case do not scale to radians
  246. or degrees; use the angle value in the range 0 to 8).  Calculate the signed
  247. angle between two successive vertexes by subtracting the angles for each
  248. vertex.  Add up all the signed angle differences, and compare to the mid-range
  249. value.
  250.  
  251. The case of a test point coincident with a polygon vertex must be explicitly
  252. checked, as the arctangent for a zero-length vector is undefined.  Another
  253. fine point is that angle differences must be wrapped in the range -180 to +180
  254. degrees.
  255.  
  256. As fond as I am :-) of this method, I still won't argue that the "count ray
  257. crossings" method is not better.  For a polygon with N edges, an optimized
  258. "count ray crossings" algorithm requires at most one multiply, one divide, and
  259. about a half-dozen add/subtract/compare operations per edge.  The "add angle
  260. differences" algorithm using the fast approximation to the arctangent requires
  261. only one divide but more than twice as many add/subtract/compare operations
  262. per edge...
  263.  
  264. ----
  265.  
  266. Sundar Narasimhan (sundar@fiber-one.ai.mit.edu) comments on Ron's post:
  267.  
  268. I think it is somewhat misleading to count worst case operations / edge and
  269. then multiply it blindly by N esp.  since the "count ray crossings" algorithm
  270. can be optimized to consider only the subset of N edges that actually have a
  271. chance of intersecting the fired ray, whereas I haven't seen any such
  272. pre-filtering done to the add angle difference algorithm.
  273.  
  274. ----
  275.  
  276. Christopher Jam (phillips@swanee.ee.uwa.oz.au) writes:
  277.  
  278. For the "count ray crossings" method, if your processor has no multiply or
  279. divide instructions, the multiply and divide may be replaced by a binary
  280. search for the point on the edge with the same y coordinate as the point being
  281. tested.  Alternatively, if you are going to draw the polygon at some stage,
  282. generate a list of points on the line for plotting, and keep these in a table
  283. to completely remove any requirements for multiplies, divides or searches.
  284. Just look up a point on the same line ;)
  285.  
  286. ----
  287.  
  288. Stuart MacMartin (sjm@bcrki65.bnr.ca) comments:
  289.  
  290. I know the purpose of your code was for a simple comparison of the two
  291. algorithms, but for production you might want to write optimal code.
  292.  
  293. The loop overhead is actually quite expensive, as I found out when I optimized
  294. someone else's implementation of this algorithm.  Most of the time is spent
  295. looking for the next y that is on/below the ray or the next y that is above
  296. the ray.  You should be able to get at lease a factor of 2 improvement by
  297. optimizing those two loops.  Call a subroutine if necessary for the deleted
  298. stuff.  (Note that subroutines can be MORE efficient because the compiler may
  299. make a better use of registers for the time-consuming part of the loop.)  Use
  300. pointers to the y rather than to the x to avoid the extra adding, and don't
  301. keep track of so many variables in the loop.
  302.  
  303. Finally, is it necessary to use doubles?  With appropriate units, will long
  304. suffice?  Just be careful if you make this switch:  if you have to have
  305. doubles in some places in your code, watch out for conversions from long to
  306. double and back.  On some platforms (definitely Apollo; I don't know about
  307. others) such casts take so long that they totally swamp anything else that is
  308. inefficient in a loop.
  309.  
  310. My code for the loop:
  311.  
  312.     stop = vertices + (numVertices << 1);
  313.  
  314.     for(y = vertices[1], p = vertices+3;  p < stop;  y = *p,p+=2) {
  315.     /* Skip all lines above */
  316.     if      (y > ay) while ((p < stop) && (*p > ay)) p += 2;
  317.     /* Skip all lines below */
  318.     else if (y < ay) while ((p < stop) && (*p < ay)) p += 2;
  319.         /* NOTE! Don't skip horizontal edges at ay! */
  320.     if (p >= stop) break;
  321.  
  322. The routine requires that the first point is duplicated as the last.
  323.  
  324. ----
  325.  
  326. Final (for now) comments, by Eric Haines:
  327.  
  328. Other people noted the barycentric test as being a way to do inside/outside
  329. testing.  The barycentric test is included below in Peter Shirley's article,
  330. and is also written up on page 390-393 of Graphics Gems, Didier Badouel's
  331. article.  You can do better than figuring out all the intermediate differences
  332. (as shown in Badouel's article), instead computing them as needed.  Also, my
  333. code worries about zero area triangles just to be safe, so it could be a bit
  334. faster without these sanity checks.
  335.  
  336. Badouel points out that triangle testing works for convex polygons:  you
  337. simply test all of the triangles, and any intersection ends the test.  Most
  338. people assume that concave triangles must be intersected using a different
  339. test.  Not so!  As Berlin pointed out (Vol 11, SIGGRAPH '85 course notes -
  340. sorry for the obscure reference!), you can test a concave polygon by checking
  341. all its triangles generated from one vertex.  If the number of triangles hit
  342. is odd, the point is inside the (potentially concave) polygon - try it out, it
  343. actually works!  You do have to test all triangles, however; if you knew the
  344. polygon was convex you can stop on the first intersection.  Also, the
  345. barycentric coordinates become somewhat meaningless, since more than one
  346. triangle can be found to overlap your test point.
  347.  
  348.  
  349. So, included in the new code (which is at the end of this issue) are two
  350. flavors of the crossings (segment) test, one which is fairly fast and
  351. readable, the other is "macmartinized" by me and runs a bit faster still.
  352. The barycentric polygon intersector is also included, and it works for all
  353. polygons (concave, self-intersecting, etc).
  354.  
  355. Random polygon testing:
  356.  
  357.              number (or range) of vertices
  358.             3        4        5        3-7        20        100
  359.  
  360. angle           57.21   69.81   86.44   82.98  303.33 1435.78
  361. barycentric        1.80    3.44    5.29    4.90   30.78  164.38
  362. crossings        2.17    2.76    3.32    3.24   12.51   60.13
  363. macmartin        1.86    2.35    2.87    2.64   11.04   52.27
  364.  
  365. inside %        6.00   12.00   13.78    9.33   26.89   41.22
  366.  
  367. Times are in microseconds per intersection test, on an HP 720 workstation.
  368. The "for" loop for repeating each test is counted into these test times
  369. (basically, I repeat each polygon/point test a number of times so that there's
  370. some reasonable amount of time to count) - not counting it just means the
  371. "crossings" tests is all that much faster.  Basically, the macmartinized
  372. crossing test wins on my machine; your mileage may vary.
  373.  
  374. Note that the barycentric intersector could be faster if the polygons are
  375. known to be convex, since then a quick out could be taken (i.e. the first hit
  376. ends testing).  I won't swear at all for the completeness of the barycentric
  377. code:  I suspect you can get into roundoff error problems for intersection
  378. points which lay exactly on some internal, invisible triangle testing edge
  379. (rare, but possible).
  380.  
  381. There are also a few hacks I haven't done on the barycentric intersector:  you
  382. could make the set of if statements into two big if statements, the variable
  383. "v0" is not all that useful, etc.  Also, if the polygon is a triangle the test
  384. could be made a special case and the "for" loop and other baggage could be
  385. eliminated (this I tried, and it resulted in about a 20% reduction in run
  386. time).  However, the code presented is at least readable, and the general
  387. behavior is the same:  this intersector gets more expensive than the crossing
  388. methods as the number of polygon vertices rises.
  389.  
  390. Looking over the branch flow analysis, I find that my test case polygons
  391. (randomly generated points) cause a lot of algebraic tests to occur when using
  392. the crossing algorithms (i.e.  the exact x intersection point has to be
  393. computed when a polygon edge goes from one quadrant to its diagonal opposite).
  394. For real polygons, this case is much less prevalent since vertices tend to be
  395. close to each other, so the polygons I've generated are more pathological than
  396. normally encountered.  For example, if the polygons generated are regular
  397. polygons inscribed in a circle of radius 1.0 and given a random rotation about
  398. the origin, the timings are
  399.  
  400. Regular polygon testing:
  401.  
  402.              number (or range) of vertices
  403.             3        4        5        3-7        20        100
  404.  
  405. angle           54.20   70.80   85.14   87.83  314.53 1522.00
  406. barycentric        2.11    3.98    5.48    5.64   27.63  144.27
  407. crossings        2.50    3.09    3.30    3.42    9.46   42.71
  408. macmartin        2.32    2.81    2.91    2.92    6.29   23.91
  409.  
  410. inside %       33.22   51.00   60.22   55.22   77.44   80.22
  411.  
  412. I'm not sure why there's any noticeable difference in the "angle summation"
  413. tests, since this test should be the same for any test point (I suspect it's
  414. just the "times()" routine's granularity).  The barycentric times change a
  415. little for better and worse, probably due to times() and to different polygon
  416. vs. point tests.  The two crossings test noticeably improve for large polygons
  417. (29% and 54% savings, respectively) - this is due to less "difficult" edges,
  418. and for the macmartin test there are now longer series of edges fully above or
  419. fully below the test point.  These tests show off the real improvement of the
  420. macmartin algorithm when testing many sided polygons.
  421.  
  422. The near-final word is that the crossings tests seems to be the most efficient
  423. overall, the angle test should generally be avoided like the plague, and the
  424. barycentric test is good for the special case of triangles (and you also
  425. get the vertex interpolant weights).  Just to add to the confusion, I talk
  426. about intersecting complex polygons in an article below; if you're using a lot
  427. of these then another intersection algorithm might be a better route to go.
  428.  
  429. -------------------------------------------------------------------------------
  430.  
  431. Polygon Intersection via Barycentric Coordinates, by Peter Shirley
  432.     (shirley@iuvax.cs.indiana.edu)
  433.  
  434. One good way to do ray triangle intersection is to use barycentric
  435. coordinates.  If the triangle has vertices p0, p1, p2, then any point in the
  436. plane containing the triangle can be represented as
  437.  
  438.     p = a*p0 + b*p2 + g*p3
  439.  
  440. and the constraint a + b + g = 1 will also hold.  If you want to interpolate
  441. colors or normals across the triangle, you can use a similar formula.  A
  442. little messing around will convince you that for points inside the triangle,
  443. a, b, and g are all positive, and outside the triangle, at least one is
  444. negative.  We can take this info, and get rid of a:
  445.  
  446.     p = p0 + b*(p1 - p0) + g*(p2-p0)
  447.  
  448. The point p is inside if b and g are positive, and (b+g) < 1.
  449.  
  450. A point on our ray can be represented as p' = o + t*v, where o is the point of
  451. origin on the ray, and v is the direction of propagation.  Plugging this into
  452. the triangle formula, we can find whether any point on the ray is also a point
  453. on the plane:
  454.  
  455.     o + t*v = p0 + b*(p1 - p0) + g*(p2-p0)
  456.  
  457. Note that this is really 3 linear equations (one for x, y and z).  You can
  458. rewrite this as a 3 by 3 linear system and solve for (t, b, g) and there is a
  459. hit if and only if:
  460.  
  461.     t > 0
  462.     b > 0
  463.     g > 0
  464.     b+g < 1
  465.  
  466. Alternatively, you can first find the equation of the plane containing the
  467. triangle and find t.  This will give you an explicit point h on the plane.
  468. You now have:
  469.  
  470.     h = p0 + b*(p1 - p0) + g*(p2-p0)
  471.  
  472. Now you have 3 equations and 2 unknowns.  Choosing any two of the equations is
  473. equivalent to projecting the problem onto one of the cartesian planes.  Watch
  474. out if the triangle is in one of the planes, because the projection might be a
  475. line segment.  You can check the surface normal to see if it is one of those
  476. cases (I just use the dimensions associated with the smallest magnitude
  477. components of the normal).
  478.  
  479. Note-- none of this is new.  GG II and the ray tracing book have other ways to
  480. do it.  Also, if your scenes are large, you are probably better off optimizing
  481. your spatial partitioning code (the part which takes longer for bigger
  482. scenes).
  483.  
  484. [For more info, see Didier Badouel's article in "Graphics Gems", p. 390-393]
  485.  
  486. -------------------------------------------------------------------------------
  487.  
  488. Many-Sided Polygon Intersection, by Eric Haines, Benjamin Zhu
  489.  
  490.  
  491. Jon Bennett (jb7m+@andrew.cmu.edu) writes:
  492.  
  493. >For a project i was working on i needed a very fast 2-D point-in-polygon
  494. >routine for a monte-carlo simulation, and came up with a variation of the
  495. >standard jordan curve theorem algorithm which ran approximately on the
  496. >order of O(n/20) when n > ~100 (for "mostly" round-ish polygons), instead
  497. >of O(n).  What I can't find, and no one here seems to know, is for large
  498. >polygons what is the best 2-D algorithm.  Everything they've heard of runs
  499. >in O(n) (I know that n and n/20 are the same "order" but the you know what
  500. >I mean). I'd like to know if there is something faster.
  501.  
  502.  
  503. You might check Preparata & Shamos's _Computational Geometry_ book, I believe
  504. they talk about faster algorithms.  Unfortunately, much of the stuff in CG
  505. tends to be things like O(K * log n), where K is something pretty large.
  506.  
  507. A simple way to test polygons with a large number of edges in O(n/K) time is
  508. to sort the edges into buckets, then find out which bucket the test point
  509. falls into.  Then you do the usual ray test, but only against those edges in
  510. the bucket.
  511.  
  512. For example, you could take a hundred edge polygon and find the Y extent in the
  513. polygon's plane.  Split this extent into, say, 20 buckets (or whatever number
  514. you like, more ==> more efficient, but also more memory and preprocessing).
  515. Now take each edge and note which buckets it's in.  As an added speed-up, sort
  516. the edges by their leftmost X values in that bucket.
  517.  
  518. Now testing can begin.  When you test a point, use the Y coordinate to find
  519. which bucket to check.  Now test each edge by the normal Jordan test against
  520. the point.  You only need to test edges to the left of the point (i.e. you are
  521. using a test ray in the -X direction), so as soon as you reach an edge whose
  522. leftmost X is greater than the point's X, you can stop testing.
  523.  
  524. The bucket sort immediately gets rid of a lot of edges, and the X test means
  525. often not having to test all edges in the bucket (it's optional icing).
  526.  
  527. If you're really into using memory and like preprocessing, you could use a
  528. grid structure to place buckets on the polygon.  Each grid cell is inside,
  529. outside, or indeterminate.  There are some tricks, but I leave these as an
  530. exercise for the reader...  Anyway, this method can be very fast, since much
  531. of the polygon's area is classified as in or out and much of the time no edges
  532. have to be tested at all.  The only limit is the grid cell resolution.  As the
  533. resolution rises the actual testing approaches constant time ( O(1)!).
  534. There's more preprocessing involved, but if you're making a lot of tests then
  535. this is worth doing.
  536.  
  537. ----
  538.  
  539. Benjamin Zhu (zhu@graphack.asd.sgi.com) comments on a similar question:
  540.  
  541. If your polygon is convex, (more generally, your polygon is star-shaped,) you
  542. can pre-process the polygon into triangle strips by connecting any point in
  543. the kernel of the polygon with each vertex of the polygon.  This takes you
  544. O(n) pre-processing time.  After that, for each point, you do a binary search
  545. in polar coordinates to locate the potential triangle where the point might
  546. lie.  Then you can determine if the point lies within this triangle, which is
  547. trivial.  See Preparata and Shamos' "Computational Geometry" for more details.
  548. Obviously, this algorithm will give you O(log(n)) time per point.  So you
  549. might consider this one if you need to solve the point-inclusion problem many
  550. times.
  551.  
  552. -------------------------------------------------------------------------------
  553.  
  554. Code for Point in Polygon Intersectors, by Eric Haines
  555.  
  556. Here it is, code for the angle test, the barycentric test, and the two
  557. crossings tests, with a main program to test their speeds.  You may need to
  558. use something other than srand()/drand48() for your random number generator,
  559. and the times() command for timing.  You'll also want to change the
  560. *_TEST_TIMES constants if you're using something slower than an HP 720
  561. workstation.  Feel free to complain about the slowness of any of the code -
  562. I'm always interested in new hacks.
  563.  
  564.  
  565. /* Point in polygon inside/outside tester.  Angle summation, barycentric
  566.  * coordinates, and ray along x-axis (crossings testing) compared.
  567.  *
  568.  * copyright 1992 by Eric Haines, 3D/Eye Inc, erich@eye.com
  569.  */
  570.  
  571. #include <math.h>
  572. #include <sys/types.h>
  573. #include <sys/param.h>
  574. #include <sys/times.h>
  575.  
  576. #define    X    0
  577. #define    Y    1
  578.  
  579. double    drand48() ;
  580.  
  581. double    AngleTimeTotal ;
  582. double    BarycentricTimeTotal ;
  583. double    CrossingsTimeTotal ;
  584. double    MacmartinTimeTotal ;
  585.  
  586. /* minimum & maximum number of polygon vertices to generate */
  587. #define    MIN_VERTS    3
  588. #define    MAX_VERTS    7
  589.  
  590. /* number of different polygons to try */
  591. #define    TEST_POLYGONS    30
  592.  
  593. /* number of different intersection points to try */
  594. #define    TEST_POINTS    30
  595.  
  596. /* number of times to try a single point vs. a polygon */
  597. /* this should be > 1 / ( HZ * approx. single test time in seconds ) */
  598. #define    ANGLE_TEST_TIMES    1000
  599. #define    BARYCENTRIC_TEST_TIMES    10000
  600. #define    CROSSINGS_TEST_TIMES    10000
  601. #define    MACMARTIN_TEST_TIMES    10000
  602.  
  603. main(argc,argv)
  604. int argc;  char *argv[];
  605. {
  606. int    i, j, numverts, inside_tot ;
  607. int    angle_flag, barycentric_flag, crossings_flag, macmartin_flag ;
  608. double    pgon[MAX_VERTS][2] ;
  609. double    point[2] ;
  610.  
  611.     srand( 12345 ) ;
  612.  
  613.     AngleTimeTotal = 0.0 ;
  614.     BarycentricTimeTotal = 0.0 ;
  615.     CrossingsTimeTotal = 0.0 ;
  616.     MacmartinTimeTotal = 0.0 ;
  617.     inside_tot = 0 ;
  618.  
  619.     for ( i = 0 ; i < TEST_POLYGONS ; i++ ) {
  620.  
  621. #ifdef CENTERED_SQUARE
  622.     /* for debugging purposes, test against a square */
  623.     numverts = 4 ;
  624.     pgon[0][X] = 0.2 ;
  625.     pgon[0][Y] = 0.2 ;
  626.     pgon[1][X] = 0.8 ;
  627.     pgon[1][Y] = 0.2 ;
  628.     pgon[2][X] = 0.8 ;
  629.     pgon[2][Y] = 0.8 ;
  630.     pgon[3][X] = 0.2 ;
  631.     pgon[3][Y] = 0.8 ;
  632. #else
  633.     /* make an arbitrary polygon fitting 0-1 range in x and y */
  634.     numverts = MIN_VERTS +
  635.         (int)(drand48() * (double)(MAX_VERTS-MIN_VERTS+1)) ;
  636.     for ( j = 0 ; j < numverts ; j++ ) {
  637.         pgon[j][X] = drand48() ;
  638.         pgon[j][Y] = drand48() ;
  639.     }
  640. #endif
  641.  
  642.     /* now try # of points against it */
  643.     for ( j = 0 ; j < TEST_POINTS ; j++ ) {
  644.         point[X] = drand48() ;
  645.         point[Y] = drand48() ;
  646.         angle_flag = angletest( pgon, numverts, point ) ;
  647.         barycentric_flag = barycentrictest( pgon, numverts, point ) ;
  648.         crossings_flag = crossingstest( pgon, numverts, point ) ;
  649.         macmartin_flag = macmartintest( pgon, numverts, point ) ;
  650.  
  651.         /* reality check */
  652.         if ( angle_flag != crossings_flag ) {
  653.         printf( "angle test says %s, crossings test says %s\n",
  654.             angle_flag ? "INSIDE" : "OUTSIDE",
  655.             crossings_flag ? "INSIDE" : "OUTSIDE" ) ;
  656.         printf( "point %g %g\n", (float)point[X], (float)point[Y] ) ;
  657.         printf( "polygon:\n" ) ;
  658.         for ( j = 0 ; j < numverts ; j++ ) {
  659.             printf( "  %g %g\n", (float)pgon[j][X], (float)pgon[j][Y]);
  660.         }
  661.         }
  662.         if ( barycentric_flag != macmartin_flag ) {
  663.         printf( "barycentric test says %s, macmartin test says %s\n",
  664.             barycentric_flag ? "INSIDE" : "OUTSIDE",
  665.             macmartin_flag ? "INSIDE" : "OUTSIDE" ) ;
  666.         printf( "point %g %g\n", (float)point[X], (float)point[Y] ) ;
  667.         printf( "polygon:\n" ) ;
  668.         for ( j = 0 ; j < numverts ; j++ ) {
  669.             printf( "  %g %g\n", (float)pgon[j][X], (float)pgon[j][Y]);
  670.         }
  671.         }
  672.  
  673.         inside_tot += crossings_flag ;
  674.     }
  675.     }
  676.     printf( "angle test time: %g microseconds per test\n",
  677.     (float)( AngleTimeTotal/(double)(TEST_POINTS*TEST_POLYGONS) ) ) ;
  678.     printf( "barycentric test time: %g microseconds per test\n",
  679.     (float)( BarycentricTimeTotal/(double)(TEST_POINTS*TEST_POLYGONS) ) ) ;
  680.     printf( "crossings test time: %g microseconds per test\n",
  681.     (float)( CrossingsTimeTotal/(double)(TEST_POINTS*TEST_POLYGONS) ) ) ;
  682.     printf( "macmartin crossings test time: %g microseconds per test\n",
  683.     (float)( MacmartinTimeTotal/(double)(TEST_POINTS*TEST_POLYGONS) ) ) ;
  684.  
  685.     printf( "%g %% of all points were inside polygons\n",
  686.     (float)inside_tot * 100.0 / (float)(TEST_POINTS*TEST_POLYGONS) ) ;
  687. }
  688.  
  689. /* sum angles of vtxN - point - vtxN+1, check if in PI to 3*PI range */
  690. int
  691. angletest( pgon, numverts, point )
  692. double    pgon[MAX_VERTS][2] ;
  693. int    numverts ;
  694. double    point[2] ;
  695. {
  696. int    i, j, inside_flag ;
  697. struct  tms     timebuf ;
  698. long    timestart ;
  699. long    timestop ;
  700. double    *vtx0, *vtx1, angle, len, vec0[2], vec1[2] ;
  701.  
  702.     /* do the test a bunch of times to get a useful time reading */
  703.     timestart = times( &timebuf ) ;
  704.     for ( i = 0 ; i < ANGLE_TEST_TIMES ; i++ ) {
  705.     /* sum the angles and see if answer mod 2*PI > PI */
  706.     vtx0 = pgon[numverts-1] ;
  707.     vec0[X] = vtx0[X] - point[X] ;
  708.     vec0[Y] = vtx0[Y] - point[Y] ;
  709.     if ( (len = hypot( vec0[X], vec0[Y] )) <= 0.0 ) {
  710.         /* point and vertex coincide */
  711.         return( 1 ) ;
  712.     }
  713.     vec0[X] /= len ;
  714.     vec0[Y] /= len ;
  715.  
  716.     angle = 0.0 ;
  717.     for ( j = 0 ; j < numverts ; j++ ) {
  718.         vtx1 = pgon[j] ;
  719.         vec1[X] = vtx1[X] - point[X] ;
  720.         vec1[Y] = vtx1[Y] - point[Y] ;
  721.         if ( (len = hypot( vec1[X], vec1[Y] )) <= 0.0 ) {
  722.         /* point and vertex coincide */
  723.         return( 1 ) ;
  724.         }
  725.         vec1[X] /= len ;
  726.         vec1[Y] /= len ;
  727.  
  728.         /* check if vec1 is to "left" or "right" of vec0 */
  729.         if ( vec0[X] * vec1[Y] - vec1[X] * vec0[Y] >= 0.0 ) {
  730.         /* add angle due to dot product of vectors */
  731.         angle += acos( vec0[X] * vec1[X] + vec0[Y] * vec1[Y] ) ;
  732.         } else {
  733.         /* subtract angle due to dot product of vectors */
  734.         angle -= acos( vec0[X] * vec1[X] + vec0[Y] * vec1[Y] ) ;
  735.         }
  736.  
  737.         /* get to next point */
  738.         vtx0 = vtx1 ;
  739.         vec0[X] = vec1[X] ;
  740.         vec0[Y] = vec1[Y] ;
  741.     }
  742.     /* test if between PI and 3*PI, 5*PI and 7*PI, etc */
  743.     /* if we care about is winding number > 0, then just:
  744.            inside_flag = fabs(angle) > M_PI ;
  745.      */
  746.     inside_flag = fmod( fabs(angle) + M_PI, 4.0*M_PI ) > 2.0*M_PI ;
  747.     }
  748.     timestop = times( &timebuf ) ;
  749.     /* time in microseconds */
  750.     AngleTimeTotal += 1000000.0 * (double)(timestop - timestart) /
  751.     (double)(HZ * ANGLE_TEST_TIMES) ;
  752.  
  753.     return (inside_flag) ;
  754. }
  755.  
  756. /* barycentric, a la Gems I, with a little efficiency tuning */
  757. int
  758. barycentrictest( pgon, numverts, point )
  759. double    pgon[MAX_VERTS][2] ;
  760. int    numverts ;
  761. double    point[2] ;
  762. {
  763. int    i, tris_hit, inside_flag, p1, p2 ;
  764. struct  tms     timebuf ;
  765. long    timestart ;
  766. long    timestop ;
  767. double    tx, ty, u0, u1, u2, v0, v1, alpha, beta, denom ;
  768.  
  769.     /* do the test a bunch of times to get a useful time reading */
  770.     timestart = times( &timebuf ) ;
  771.     for ( i = 0 ; i < BARYCENTRIC_TEST_TIMES ; i++ ) {
  772.  
  773.     tx = point[X] ;
  774.     ty = point[Y] ;
  775.  
  776.     tris_hit = 0 ;
  777.  
  778.     for ( p1 = 1, p2 = 2 ; p2 < numverts ; p1++, p2++ ) {
  779.  
  780.         if ( ( u1 = pgon[0][X] - pgon[p2][X] ) == 0.0 ) {
  781.  
  782.         /* zero area test - optional */
  783.         if ( ( u2 = pgon[p1][X] - pgon[p2][X] ) == 0.0 ) {
  784.             goto NextTri;
  785.         }
  786.  
  787.         /* Compute intersection point */
  788.         if ( ( ( beta = ( tx - pgon[p2][X] ) / u2 ) < 0.0 ) ||
  789.                ( beta > 1.0 ) ) {
  790.  
  791.             goto NextTri;
  792.         }
  793.  
  794.         if ( ( v1 = pgon[0][Y] - pgon[p2][Y] ) == 0.0 ) {
  795.             goto NextTri;
  796.         }
  797.  
  798.         if ( ( alpha = ( ty - pgon[p2][Y] - beta *
  799.             ( pgon[p1][Y] - pgon[p2][Y] ) ) / v1 ) < 0.0 ) {
  800.             goto NextTri;
  801.         }
  802.  
  803.         } else {
  804.         if ( ( denom = ( pgon[p1][Y] - pgon[p2][Y] ) * u1 -
  805.             ( u2 = pgon[p1][X] - pgon[p2][X] ) *
  806.             ( v1 = pgon[0][Y] - pgon[p2][Y] ) ) == 0.0 ) {
  807.  
  808.             goto NextTri;
  809.         }
  810.  
  811.         /* Compute intersection point & subtract 0 vertex */
  812.         u0 = tx - pgon[p2][X] ;
  813.         v0 = ty - pgon[p2][Y] ;
  814.  
  815.         if ( ( ( ( beta = ( v0 * u1 - u0 * v1 ) / denom ) ) < 0.0 ) ||
  816.                ( beta > 1.0 ) ) {
  817.  
  818.             goto NextTri;
  819.         }
  820.         if ( ( alpha = ( u0 - beta * u2 ) / u1 ) < 0.0 ) {
  821.             goto NextTri;
  822.         }
  823.         }
  824.  
  825.         /* check gamma */
  826.         if ( alpha + beta <= 1.0 ) {
  827.         /* survived */
  828.         tris_hit++ ;
  829.         }
  830.  
  831.         NextTri: ;
  832.     }
  833.     inside_flag = tris_hit & 0x1 ;
  834.     }
  835.     timestop = times( &timebuf ) ;
  836.     /* time in microseconds */
  837.     BarycentricTimeTotal += 1000000.0 * (double)(timestop - timestart) /
  838.     (double)(HZ * BARYCENTRIC_TEST_TIMES) ;
  839.  
  840.     return (inside_flag) ;
  841. }
  842.  
  843. /* shoot a test ray along +X axis - slower version, less messy */
  844. int
  845. crossingstest( pgon, numverts, point )
  846. double    pgon[MAX_VERTS][2] ;
  847. int    numverts ;
  848. double    point[2] ;
  849. {
  850. int    i, j, inside_flag, xflag0 ;
  851. struct  tms     timebuf ;
  852. long    timestart ;
  853. long    timestop ;
  854. double    *vtx0, *vtx1, dv0 ;
  855. int    crossings, yflag0, yflag1 ;
  856.  
  857.     /* do the test a bunch of times to get a useful time reading */
  858.     timestart = times( &timebuf ) ;
  859.     for ( i = 0 ; i < CROSSINGS_TEST_TIMES ; i++ ) {
  860.  
  861.     vtx0 = pgon[numverts-1] ;
  862.     /* get test bit for above/below Y axis */
  863.     yflag0 = ( dv0 = vtx0[Y] - point[Y] ) >= 0.0 ;
  864.  
  865.     crossings = 0 ;
  866.     for ( j = 0 ; j < numverts ; j++ ) {
  867.         /* cleverness:  bobble between filling endpoints of edges, so
  868.          * that the previous edge's shared endpoint is maintained.
  869.          */
  870.         if ( j & 0x1 ) {
  871.         vtx0 = pgon[j] ;
  872.         yflag0 = ( dv0 = vtx0[Y] - point[Y] ) >= 0.0 ;
  873.         } else {
  874.         vtx1 = pgon[j] ;
  875.         yflag1 = ( vtx1[Y] >= point[Y] ) ;
  876.         }
  877.  
  878.         /* check if points not both above/below X axis - can't hit ray */
  879.         if ( yflag0 != yflag1 ) {
  880.         /* check if points on same side of Y axis */
  881.         if ( ( xflag0 = ( vtx0[X] >= point[X] ) ) ==
  882.              ( vtx1[X] >= point[X] ) ) {
  883.  
  884.             if ( xflag0 ) crossings++ ;
  885.         } else {
  886.             /* compute intersection of pgon segment with X ray, note
  887.              * if > point's X.
  888.              */
  889.             crossings += (vtx0[X] -
  890.             dv0*( vtx1[X]-vtx0[X])/(vtx1[Y]-vtx0[Y])) >= point[X] ;
  891.         }
  892.         }
  893.     }
  894.     /* test if crossings is odd */
  895.     /* if we care about is winding number > 0, then just:
  896.            inside_flag = crossings > 0 ;
  897.      */
  898.     inside_flag = crossings & 0x01 ;
  899.     }
  900.     timestop = times( &timebuf ) ;
  901.     /* time in microseconds */
  902.     CrossingsTimeTotal += 1000000.0 * (double)(timestop - timestart) /
  903.     (double)(HZ * CROSSINGS_TEST_TIMES) ;
  904.  
  905.     return (inside_flag) ;
  906. }
  907.  
  908. /* shoot a test ray along +X axis - macmartinized by me, a bit messier */
  909. int
  910. macmartintest( pgon, numverts, point )
  911. double    pgon[MAX_VERTS][2] ;
  912. int    numverts ;
  913. double    point[2] ;
  914. {
  915. int    i, inside_flag, xflag0 ;
  916. struct  tms     timebuf ;
  917. long    timestart ;
  918. long    timestop ;
  919. double    *p, *stop ;
  920. int    crossings ;
  921. double    tx, ty, y ;
  922.  
  923.     /* do the test a bunch of times to get a useful time reading */
  924.     timestart = times( &timebuf ) ;
  925.     for ( i = 0 ; i < MACMARTIN_TEST_TIMES ; i++ ) {
  926.  
  927.     crossings = 0 ;
  928.  
  929.     tx = point[X] ;
  930.     ty = point[Y] ;
  931.     y = pgon[numverts-1][Y] ;
  932.  
  933.     p = (double *)pgon + 1 ;
  934.     if ( ( y >= ty ) != ( *p >= ty ) ) {
  935.         /* x crossing */
  936.         if ( ( xflag0 = ( pgon[numverts-1][X] >= tx ) ) ==
  937.          ( *(double *)pgon >= tx ) ) {
  938.  
  939.         if ( xflag0 ) crossings++ ;
  940.         } else {
  941.         /* compute intersection of pgon segment with X ray, note
  942.          * if > point's X.
  943.          */
  944.         crossings += ( pgon[numverts-1][X] -
  945.         (y-ty)*( *(double *)pgon - pgon[numverts-1][X])/(*p-y)) >= tx ;
  946.         }
  947.     }
  948.  
  949.     stop = pgon[numverts] ;
  950.  
  951.     for ( y=*p,p += 2 ; p < stop ; y=*p,p+=2) {
  952.  
  953.         if ( y >= ty ) {
  954.         while ( (p < stop) && (*p >= ty) ) p+=2 ;
  955.         if ( p >= stop ) goto Exit ;
  956.         /* y crosses */
  957.         if ( ( xflag0 = ( *(p-3) >= tx ) ) ==
  958.              ( *(p-1) >= tx ) ) {
  959.  
  960.             if ( xflag0 ) crossings++ ;
  961.         } else {
  962.             /* compute intersection of pgon segment with X ray, note
  963.              * if > point's X.
  964.              */
  965.             crossings += ( *(p-3) -
  966.             (*(p-2)-ty)*( *(p-1)-*(p-3))/(*p-*(p-2))) >= tx ;
  967.         }
  968.         } else {
  969.         while ( (p < stop) && (*p < ty)) p+=2 ;
  970.         if ( p >= stop ) goto Exit ;
  971.         /* y crosses */
  972.         if ( ( xflag0 = ( *(p-3) >= tx ) ) ==
  973.              ( *(p-1) >= tx ) ) {
  974.  
  975.             if ( xflag0 ) crossings++ ;
  976.         } else {
  977.             /* compute intersection of pgon segment with X ray, note
  978.              * if > point's X.
  979.              */
  980.             crossings += ( *(p-3) -
  981.             (*(p-2)-ty)*( *(p-1)-*(p-3))/(*p-*(p-2))) >= tx ;
  982.         }
  983.         }
  984.     }
  985.  
  986.     Exit:
  987.     /* test if crossings is odd */
  988.     /* if we care about is winding number > 0, then just:
  989.            inside_flag = crossings > 0 ;
  990.      */
  991.     inside_flag = crossings & 0x01 ;
  992.     }
  993.     timestop = times( &timebuf ) ;
  994.     /* time in microseconds */
  995.     MacmartinTimeTotal += 1000000.0 * (double)(timestop - timestart) /
  996.     (double)(HZ * MACMARTIN_TEST_TIMES) ;
  997.  
  998.     return (inside_flag) ;
  999. }
  1000.